//
//  CustomBarButton.m
//  飞波
//
//  Created by 开发 on 11-8-3.
//  Copyright 2011 Feibo Inc. All rights reserved.
//

#import "CustomBarButtonItem.h"

@implementation CustomBarButtonItem

- (id)initWithTitle:(NSString *)ti style:(UIBarButtonItemCustomStyle)st target:(id)tar action:(SEL)ac
{	
	UIImage * barButtonBackImage = nil;
	UIImage * barButtonBackSelectedImage = nil;
	UIButton *barButton = [[UIButton alloc] init];
	CGFloat buttonWidth = 0.0f;
	switch (st) {
		case LeftBarButtonItemBackStyle:
			barButtonBackImage = [[UIImage imageNamed:@"ios_common_back_normal.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:0];
			barButtonBackSelectedImage = [[UIImage imageNamed:@"ios_common_back_pressed.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
			CGSize size = [ti sizeWithFont:[UIFont systemFontOfSize:13.0f] 
						 constrainedToSize:CGSizeMake(60.0f, 10.0f) 
							 lineBreakMode:UILineBreakModeCharacterWrap];
			buttonWidth = size.width + 20.0f;
			break;
		case LeftBarButtonItemHomeStyle:
			barButtonBackImage = [[UIImage imageNamed:@"ios_common_titlebar_logo.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:0];
			barButtonBackSelectedImage = [[UIImage imageNamed:@"ios_common_titlebar_logo.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:0];
			buttonWidth = barButtonBackImage.size.width;
			break;
		default:
			break;
	}
	barButton.frame = CGRectMake(0,0,buttonWidth,barButtonBackImage.size.height);
	[barButton setBackgroundImage:barButtonBackImage forState:UIControlStateNormal];
	[barButton setBackgroundImage:barButtonBackSelectedImage forState:UIControlStateHighlighted];
	[barButton setTitle:ti forState:UIControlStateNormal];
	[barButton.titleLabel setFont:[UIFont systemFontOfSize:13.0]];	
	[barButton setBackgroundColor:[UIColor clearColor]];	
	[barButton addTarget:tar action:ac forControlEvents:UIControlEventTouchUpInside];

	self = [super initWithCustomView:barButton];

	[barButton release];
	
	return self;
}

- (id)initWithBarButtonItem:(UIBarButtonItem *)barItem target:(id)target action:(SEL)action{
	UIButton *customButton = (UIButton *)barItem.customView;
	[customButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
	self = [super initWithCustomView:customButton];
	return self;
}

- (id)initWithFrame:(CGRect)rect image:(UIImage *)image selectedImage:(UIImage *)selectedImage target:(id)target action:(SEL)action
{
	UIButton *barButton = [[UIButton alloc] init];
	barButton.frame = rect;
	[barButton setBackgroundImage:image forState:UIControlStateNormal];
	[barButton setBackgroundImage:selectedImage forState:UIControlStateHighlighted];
	[barButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
	
	self = [super initWithCustomView:barButton];
	
	[barButton release];
	
	return self;
}

@end
